﻿using System;
using System.Configuration;
using System.Linq;
using System.Web.UI.WebControls;
using Controllers;

namespace Web
{
    public partial class DeptEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
                var depts = ctx.ExecuteQuery<DeptDTO>(@"with t as (select Id,Pid,cast(Text as nvarchar(500)) Text,OrderNo,1 lvl,cast(OrderNo as nvarchar(50)) orderStr,IsValid from Depts where Pid is null and IsValid=1
union all
select d.Id,d.Pid,cast(REPLICATE('---',t.lvl)+d.Text as nvarchar(500)),
d.OrderNo,t.lvl+1,cast(t.orderStr+cast(d.OrderNo as nvarchar(50)) as nvarchar(50)),d.IsValid
from Depts d,t where d.Pid=t.id and d.IsValid=1
)
  select Id,Text from t order by orderStr;");
                Pid.DataSource = depts;
                Pid.DataTextField = "Text";
                Pid.DataValueField = "Id";
                Pid.DataBind();
                Pid.Items.Insert(0,new ListItem("",""));

                string id = Request.QueryString["id"];
                if (!string.IsNullOrEmpty(id))
                {
                    Depts dept = ctx.Depts.Single(r => r.Id == int.Parse(id));
                    Pid.Value = dept.Pid.ToString();
                    Text.Value = dept.Text;
                    Remarks.Value = dept.Remarks;
                    OrderNo.Value = dept.OrderNo.ToString();
                    if (dept.IsValid)
                        IsValid.Items[0].Selected = true;
                    else
                        IsValid.Items[1].Selected = true;
                }
            }
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            ApolloOaDataContext ctx = new ApolloOaDataContext(ConfigurationManager.ConnectionStrings["SqlConnectionString"].ConnectionString);
            Depts dept;
            string id = Request.QueryString["id"];
            if (!string.IsNullOrWhiteSpace(id))
            {
                dept = ctx.Depts.Single(r => r.Id == int.Parse(id));
            }
            else
            {
                dept = new Depts();
                ctx.Depts.InsertOnSubmit(dept);
            }
            if(!string.IsNullOrWhiteSpace(Pid.Value))
            {
                dept.Pid = int.Parse(Pid.Value);
            }
            else
            {
                dept.Pid =null;
            }
            dept.Text = Text.Value;
            dept.Remarks = Remarks.Value;
            dept.OrderNo = int.Parse(OrderNo.Value);
            dept.IsValid = IsValid.Items[0].Selected;
            ctx.SubmitChanges();
            Response.Write("<script>window.returnValue='Succeed';window.close();</script>");
        }
    }
}